package engine

import (
	"context"
	"github.com/pkg/errors"
	"time"
)

func delayRun(ctx context.Context, do func(), delay time.Duration) context.CancelFunc {
	delayCtx, cancel := context.WithTimeout(context.Background(), delay)
	go func() {
		select {
		case <-ctx.Done():
			cancel()
		case <-delayCtx.Done():
			switch delayCtx.Err() {
			case context.DeadlineExceeded:
				do()
			case context.Canceled:
			}
		}
	}()
	return cancel
}

func properRun(ctx context.Context, functions ...func(ctx context.Context) error) error {
	for _, function := range functions {
		if err := function(ctx); err != nil {
			return errors.WithStack(err)
		}
	}
	return nil
}

type ProperFunc = func(ctx2 context.Context) error
